
var Tenant = function() {

    var datalist_url = $('.datalist_url').val();
    var view_url = $('.view_url').val();
    var renewalFee_url = $('.renewalFee_url').val();
    var enable_url = $('.enable_url').val();
    var disable_url = $('.disable_url').val();
    var edit_url = $('.edit_url').val();
    var redirect_url = $('.redirect_url').val();
    var agentList_url = $('.agentList_url').val();
    var district_url = $('.district_url').val();


    var  init_datetimepicker = function(obj, languages) {
        if(obj.length > 0){
            var nowDate = new Date();
            var startDate = new Date();
            // 获取当前年
            var year = nowDate.getFullYear();
            // 获取当前月
            var month = nowDate.getMonth() + 1;
            // 获取当前日
            var date = nowDate.getDate();
            var h = nowDate.getHours(); // 获取当前小时数(0-23)
            var m = nowDate.getMinutes(); // 获取当前分钟数(0-59)
            var s = nowDate.getSeconds();
            var endDate = (year+10) + '-' + month + '-' + date + ' ' + h + ':' + m + ':' + s;
            //console.log(startDate);
            console.log(endDate);
            obj.datetimepicker({
                language: languages,
                format: 'yyyy-mm-dd hh:ii:ss',
                startDate: startDate,
                endDate: endDate,
                autoclose: true
            });
        }
    };

    var initTable = function() {
        var table = $('#data-table');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                },
                "autoWidth": false,
                "columns": [
                    {"data": "code"},
                    {"data": "name"},
                    {"data": "category"},
                    {
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            if(row.province){
                                return row.province + ' - ' + row.city;
                            }else{
                                return '';
                            }
                        }
                    },
                    {"data": "loginName"},
                    {"data": "agentName"},
                    {
                        "width": "20%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var _html = '<button type="button" class="btn btn-info detail-btn">详情</button>' +
                                '<a href="'+edit_url+'?id='+encodeURIComponent(row.id)+'" type="button" class="btn btn-success">编辑</a>' +
                                '<button type="button" class="btn purple renewalFee-btn">续费</button>';
                            if(row.isActive == 1){
                                _html += '<button type="button" class="btn btn-danger disable-btn">禁用</button>';
                            }else{
                                _html += '<button type="button" class="btn btn-warning enable-btn">启用</button>';
                            }

                            return _html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/agent/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": false,
                "stateSaveParams": function (settings, data) {
                    /*var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }*/
                },
                "order": [
                    [0, "desc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [1, 2, 3, 4, 5, 6]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var param = $('#search').serializeObject();

            tableSearch(table, param);
        });

        // 详情
        table.on('click', '.detail-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var url = view_url;
            var data = {'id': id};
            $.ajax({
                url: url,
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function (data) {
                    if (data.status == 1) {
                        var _html = data.data;
                        $('#detail-modal').find('.modal-body').empty().html(_html);
                        $('#detail-modal').modal('show');
                    }else{
                        layer.msg(data.msg);
                    }
                }
            });
        });

        // 续费
        table.on('click', '.renewalFee-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var url = renewalFee_url;
            var data = {'id': id};
            $.ajax({
                url: url,
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function (data) {
                    if (data.status == 1) {
                        var _html = data.data;
                        if($('body').find('#renewalFee-modal').length){
                            $('body').find('#renewalFee-modal').remove();
                        }

                        $('body').append(_html);
                        $('#renewalFee-modal').modal('show');
                    }else{
                        layer.msg(data.msg);
                    }
                }
            });
        });

        // 禁用
        table.on('click', '.disable-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要禁用？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();
            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function (index) {
                    layer.close(index);
                    layer.load(2, {shade: [0.8,'#000000']}); // 打开loading

                    var url = disable_url;
                    var data = {'id': id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType: 'json',
                        success: function (data) {
                            layer.closeAll('loading'); // 关闭loading
                            layer.msg(data.msg);
                            if(data.status == 1){
                                window.location.reload();
                            }
                        }
                    });
                }
            );
        });

        // 启用
        table.on('click', '.enable-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要启用？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();
            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function (index) {
                    layer.close(index);
                    layer.load(2, {shade: [0.8,'#000000']}); // 打开loading

                    var url = enable_url;
                    var data = {'id': id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType: 'json',
                        success: function (data) {
                            layer.closeAll('loading'); // 关闭loading
                            layer.msg(data.msg);
                            if(data.status == 1){
                                window.location.reload();
                            }
                        }
                    });
                }
            );
        });

    };

    var agentTable = function() {
        var table = $('#agent_table');
        var id = $('input[name=id]').val();

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: agentList_url,
                    data: {'id':id}
                },
                "autoWidth": false,
                "columns": [
                    {"data": "name"},
                    {"data": "levelName"},
                    /*{"data": "fullAddress"},*/
                    {
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            if(row.province){
                                return row.province + ' - ' + row.city;
                            }else{
                                return '';
                            }
                        }
                    },
                    {
                        "width": "20%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            return '<button type="button" class="btn purple doSelect">选择</button>';
                        }
                    }
                ],
                "language": {
                    url: '/public/static/agent/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": false,
                "stateSaveParams": function (settings, data) {
                    /*var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }*/
                },
                "columnDefs": [{
                    "orderable": false,
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                    "<t>" +
                    "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var name = $("#search input[name='name']").val();
            var param = {
                "name" : name,
            };

            tableSearch(table, param);
        });

        // 选择
        table.on('click', '.doSelect', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var name = dataArr[0].name;

            $('input[name=createOper]').val(id);
            $('#createOper').val(name);
            $('#agent-modal').modal('hide');
        });
    };

    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };


    return {
        init: function() {
            init_datetimepicker($(".datetime-picker"), 'zh-CN');
            initTable();
            agentTable();

            this.onEvent();
        },

        onEvent : function(){

            // 续费提交
            $(document).on('click', '.renewalFee-save', function () {
                var amount = $('input[name=renewal_money]').val();
                if(!mdTool.validate(amount, 'two') || amount == 0){
                    layer.msg('充值金额应大于0，且小数点后只有两位！');
                    $('input[name=renewal_money]').focus();
                    return false;
                }

                $('#renewalFee-modal').modal('hide');
                var url = $('#renewalFee-modal').find('#ajax-form').attr('action');
                var data = $('#renewalFee-modal').find('#ajax-form').serialize();
                //console.log(data);
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    dataType: 'json',
                    success: function (data) {
                        layer.msg(data.msg);
                        window.location.reload();
                    }
                });
            });

            // 所在地区选择
            $('.district').on('click', function(){
                var url = district_url;
                var data = {};
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    dataType: 'json',
                    success: function (data) {
                        if (data.status == 1) {
                            var _html = data.data;
                            if($('body').find('#district-modal').length){
                                $('body').find('#district-modal').remove();
                            }

                            $('body').append(_html);
                            $('#district-modal').modal('show');
                        }else{
                            layer.msg(data.msg);
                        }
                    }
                });
            });
            $(document).on('click', '.confirm-district', function () {
                var obj = $('#district-modal').find('input[name=district]');
                var check_val = [];
                for(i in obj){
                    if(obj[i].checked){
                        check_val.push(obj[i].value);
                    }
                }
                //console.log(check_val);
                $('.district').val(check_val);
                $('#district-modal').modal('hide');
            });

            /**
             * 表单提交
             */
            $('.save-btn').on('click', function () {
                var _form = $('#ajax-form');
                //var _formData = $('#ajax-form').serializeObject();
                //var createOper = ajaxForm.createOper.value;
                var createOper = $('input[name=createOper]').val();

                if(createOper.trim() == ''){
                    layer.msg('请选择所属代理商！');
                    return false;
                }
                if(ajaxForm.name.value.trim() == ''){
                    layer.msg('商户名称不能为空！');
                    ajaxForm.name.focus();
                    return false;
                }
                if(ajaxForm.name.value.length > 40){
                    layer.msg('商户名称最长为40个字符！');
                    ajaxForm.name.focus();
                    return false;
                }
                if(!mdTool.validate(ajaxForm.category.value, 'require')){
                    layer.msg('请选择经营类目！');
                    return false;
                }
                var province = $('input[name=province]').val();
                if(!mdTool.validate(province, 'require') || province == '省份'){
                    layer.msg('请选择省份！');
                    return false;
                }
                var city = $('input[name=city]').val();
                if(!mdTool.validate(city, 'require') || city == '地级市'){
                    layer.msg('请选择城市！');
                    return false;
                }
                if(ajaxForm.stopUseDate.value.trim() == ''){
                    layer.msg('请输入到期时间！');
                    ajaxForm.stopUseDate.focus();
                    return false;
                }
                if(ajaxForm.loginName.value.trim() == ''){
                    layer.msg('账号不能为空！');
                    ajaxForm.loginName.focus();
                    return false;
                }
                if(ajaxForm.loginName.value.length > 11){
                    layer.msg('账号最长为11个字符！');
                    ajaxForm.loginName.focus();
                    return false;
                }
                // 添加时验证
                if(!$('input[name=ori_password]').val()){
                    if(ajaxForm.password.value.trim() == ''){
                        layer.msg('密码不能为空！');
                        ajaxForm.password.focus();
                        return false;
                    }
                }
                if(ajaxForm.password.value.trim()){
                    if(ajaxForm.password.value.length < 6 || ajaxForm.password.value.length > 12){
                        layer.msg('密码长度在6-12位之间！');
                        ajaxForm.password.focus();
                        return false;
                    }
                    if(ajaxForm.password.value != ajaxForm.confirm_password.value){
                        layer.msg('两次密码不一致！');
                        ajaxForm.confirm_password.focus();
                        return false;
                    }
                }

                if(!mdTool.validate(ajaxForm.phone.value, 'phone')){
                    layer.msg('手机号格式不正确！');
                    ajaxForm.phone.focus();
                    return false;
                }

                var url = _form.attr('action');
                var data = _form.serialize();
                layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    dataType : 'json',
                    success: function (data) {
                        layer.closeAll('loading'); // 关闭loading
                        layer.msg(data.msg);
                        if(data.status == 1){
                            window.location.href = redirect_url;
                        }
                    }
                });
                return false;
            });
        }
    };

}();


$(function() {
    Tenant.init();

});
